#include "test_httpd.h"

int main(int argc, char **argv)
{
	//init_daemon(argv[0],LOG_INFO);
    
    HttpServerCfg::load(HTTPSERVER_CFG_FILE_PATH);
    struct HttpServerCfgDef cfg = HttpServerCfg::getHttpServerCfgDef();
    
    Socket* listener = new Socket();
    if (!listener->init(cfg.ip.c_str(), cfg.port, cfg.back)) {
        wrtinfomsg("socket create error");
        return -1;
    }//重连功能
    
    while (1)
	{
        int clientfd = listener->in_event();
        if (clientfd < 0)
		{
			wrtinfomsg("accept");
            return -1;
		}
        
      	//fork a new process to deal with the connect ,the parent continue wait for new connect
       pid_t pid;  
	   if((pid=fork()) == -1)
	   {
			wrtinfomsg("fork");
           return -1;
		}
        
	   if (pid == 0)
	   {
            listener->close();
           
            char buffer[MAXBUF + 1];
            bzero(buffer, MAXBUF + 1);
            if ((recv(clientfd, buffer, MAXBUF, 0)) > 0)
			{
                FILE *ClientFP = fdopen(clientfd, "w");
                if (ClientFP == NULL) 
				{
					wrtinfomsg("fdopen");
					exit(EXIT_FAILURE);
                } 
				else 
				{
                    char Req[MAXPATH + 1] = "";
                    sscanf(buffer, "GET %s HTTP", Req);
                    bzero(buffer, MAXBUF + 1);
                    sprintf(buffer, "Reuquest get the file: \"%s\"\n", Req);
                    wrtinfomsg(buffer);
                    
                    GiveResponse(ClientFP, Req);
                    fclose(ClientFP);
                }
            }
            exit(EXIT_SUCCESS);
        }
		else
        {
			close(clientfd);
			continue;
		}
    }
    
    listener->close();
    return 0;
} 

